<?php
/**
 * User: @lixu
 * Date: 2019-05-29
 * Time: 17:20
 */

namespace Biz\service\wiki;

use Biz\module\Classes\wikiTab\WikiTab;
use Doraemon\cache\Wiki\SearchBrandTmp as cSearchBrandTmp;
use Doraemon\service\es\EsWiki;
use Doraemon\service\statSign\Basic as statSign;
use Doraemon\tools\HhzClient;
use Doraemon\tools\ParticipleKeyword;

class Search extends WikiTab
{
    const TAB_TYPE = 'wiki_search';
    const PAGE_SIZE = null;

    const BRAND_KEYWORDS = array(
        "奥田",
        "法恩莎",
//            "宜家"
    );

    const SAVE_MAX_PAGE = 5;

    const PAGESIZE = 20;

    const BATCH_PAGESIZE = self::PAGESIZE * self::SAVE_MAX_PAGE;

    private static $seeKey = null;

    public static function getList($keyword, $sortType, $page, $uid)
    {
        $result = self::getWikiIdList(['keyword' => $keyword, 'sort_type' => $sortType], $page);
        if ($result['rows']) {
            $list = Wiki::getCompleteWikiList($result['rows'], $uid);
            $list = array_values($list);
            $list = self::addStatSign($list, $keyword);
            return ['is_over' => $result['is_over'], 'list' => $list];
        }

        $result = self::getWikiIdList(['uid' => $uid], $page, 20, GoodThing::TAB_TYPE);
        if ($result['rows']) {
            $recommendList = Wiki::getCompleteWikiList($result['rows'], $uid);
            return ['is_over' => $result['is_over'], 'recommend_list' => array_values($recommendList)];
        }

        return ['is_over' => 1, 'list' => []];
    }

    public static function addStatSign($list, $keyword, $searchRequestId = "", $passBackData = "", $from = "")
    {
        $historyCount = 0;
        if ($passBackData) {
            $passBackDataArr = json_decode($passBackData, true);
            $historyCount = isset($passBackDataArr["history_count"]) ? $passBackDataArr["history_count"] : 0;
        }

        foreach ($list as $key => $row) {
            $historyCount++;
            $statSignParams = array();
            if ($searchRequestId) {
                $statSignParams["search_request_id"] = $searchRequestId;
                $statSignParams["position"] = $historyCount;
            }

            if ($from == "publish_wiki_search") {
                $list[$key]['statSign'] = statSign::genStatSign(statSign::MODULE_PUB_WIKI_SEARCH_PAGE_WIKI_CARD, [
                    statSign::EXTEND_KEY_OBJ_ID => $row['basic_id'],
                    statSign::EXTEND_KEY_OBJ_TYPE => \Doraemon\tools\BlockType::TYPE_WIKI_BASIC,
                    statSign::EXTEND_KEY_KEY_WORD => $keyword
                ], $statSignParams);
            } else {
                $list[$key]['statSign'] = statSign::genStatSign(statSign::MODULE_SEARCH_WIKI_CARD, [
                    statSign::EXTEND_KEY_OBJ_ID => $row['basic_id'],
                    statSign::EXTEND_KEY_OBJ_TYPE => \Doraemon\tools\BlockType::TYPE_WIKI_BASIC,
                    statSign::EXTEND_KEY_KEY_WORD => $keyword
                ], $statSignParams);
            }
        }

        return $list;
    }

    // https://jira.haohaozhu.me/browse/HHZML-574
    public static function searchByBrandKeyword($brandId, $keyword, $page)
    {
        $isOver = 1;

        self::setSeeKey($page, $keyword, $brandId);
        // 判断搜索内容key存不存在
        if (cSearchBrandTmp::SearchKeyExist(self::getSeeKey())) {
            list($offsetStart, $offsetEnd) = self::getOffset($page);

            $searchIds = cSearchBrandTmp::getSearchData(self::getSeeKey(), $offsetStart, $offsetEnd);
            $searchIds = is_array($searchIds) && $searchIds ? $searchIds : array();

            // 取出的内容为空 由于主从缓存删除key有延迟 重新生成值
            if (empty($searchIds)) {
                list($searchIds, $isOver) = self::searchWikiIds($keyword, $brandId, $page, self::BATCH_PAGESIZE);
            } else {
                $filterSearchIds = array_filter($searchIds);
                if (is_array($filterSearchIds) && $filterSearchIds) {
                    // 用原始的数据进行判断是否没有数据了
                    if (count($searchIds) >= self::PAGESIZE) {
                        $isOver = 0;
                    }
                }
                // 使用过滤的数据进行下面的操作
                $searchIds = $filterSearchIds;
            }
        } else {
            // key不存在开始生成缓存 生成数据
            list($searchIds, $isOver) = self::searchWikiIds($keyword, $brandId, $page, self::BATCH_PAGESIZE);
        }

        if ($searchIds) {
            $list = Wiki::getCompleteWikiList($searchIds, HhzClient::getUid());
            $list = array_values($list);
            $list = self::addStatSign($list, $keyword);
            return ['is_over' => $isOver, 'list' => $list];
        }

        return ['is_over' => $isOver, 'list' => []];
    }

    // 构建wiki数据
    public static function searchWikiIds($keyword, $brandId, $page, $pagesize)
    {
        $resetPage = self::SAVE_MAX_PAGE * (int)(($page - 1) / self::SAVE_MAX_PAGE) + 1;
        $start = ($resetPage - 1) * self::PAGESIZE;

        $handleKeyword = ParticipleKeyword::getParticipleKeyword($keyword);
        $params = array(
            "keyword" => $keyword,
            "handle_keyword" => $handleKeyword,
            "brand_id" => $brandId,
            "start" => $start,
            "page" => $page,
            "page_size" => $pagesize,
            "sort" => "hot",
//                "fl" => "id"
        );

        $result = EsWiki::searchByBrandKeyword($params);

        $isOver = 1;
        $result['rows'] = is_array($result['rows']) && $result['rows'] ? $result['rows'] : array();

        $searchIds = array();
        if (is_array($result['rows']) && $result['rows']) {
            $allSearchIds = $result['rows'];
            // 重新计算偏移量
            list($offsetStart, $offsetEnd) = self::getOffset($page);

            $cacheData = array();
            $offset = $start;
            foreach ($allSearchIds as $id) {
                $cacheData[$id] = $offset;
                $offset++;
            }

            if (is_array($cacheData) && $cacheData) {
                // 设置查询缓存
                cSearchBrandTmp::setSearchData(self::getSeeKey(), $cacheData);
                cSearchBrandTmp::setSearchKeyExpire(self::getSeeKey());
            }

            $searchIds = array_slice($allSearchIds, $offsetStart, self::PAGESIZE);
        } else {
            // 当获取不到值时 设置key为空 缓存时间内不再查数据 减少查询次数
            cSearchBrandTmp::setSearchKeyForEmpty(self::getSeeKey());
            cSearchBrandTmp::setSearchKeyExpire(self::getSeeKey());
        }

        if (count($searchIds) >= self::PAGESIZE) {
            $isOver = 0;
        }

        return array($searchIds, $isOver);
    }

    // 判断搜索词 是否 包含 指定品牌词
    public static function isBrandSearchWord($searchWords)
    {
        $flag = false;
        $brandKeywords = self::BRAND_KEYWORDS;

        foreach ($brandKeywords as $brandKeyword) {
            if (strpos($searchWords, $brandKeyword) !== false) {
                $flag = true;
            }
        }

        return $flag;
    }

    // 设置Wiki 搜索缓存key
    public static function setSeeKey($page, $keyword, $brandId)
    {
        $savePageKey = (int)(($page - 1) / self::SAVE_MAX_PAGE) + 1;

        self::$seeKey = $keyword . "-" . $savePageKey . "-B" . $brandId;
    }

    // 获取Wiki 搜索缓存key
    public static function getSeeKey()
    {
        return self::$seeKey;
    }

    // 获取缓存偏移量
    public static function getOffset($page)
    {
        $showPageSize = self::PAGESIZE;

        $resetPage = ($page - 1) % self::SAVE_MAX_PAGE;
        $start = ($resetPage) * $showPageSize;
        $end = $start + $showPageSize - 1;

        return array(
            $start,
            $end
        );
    }
}